package com.mofofa.maozy.launch

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mofofa.maozy.ProjectApplication
import com.mofofa.maozy.R
import com.mofofa.maozy.base.BaseActivity
import com.mofofa.maozy.data.ReqBase
import com.mofofa.maozy.data.ReqDoLogin
import com.mofofa.maozy.databinding.ActivityMaozyInputMobileBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.*
import com.mofofa.maozy.network.ApiToolReposity
import com.mofofa.maozy.network.ApiUrl
import com.mofofa.maozy.utils.AppConfigUtil
import com.mofofa.maozy.utils.UsageCountryUtil
import com.mofofa.maozy.utils.UserStateUtil
import com.mofofa.maozy.utils.analytics.util.AnalyticsUtil

/** 登录-输入手机号页 */
@SuppressLint("CustomSplashScreen")
class LoginInputMobileActivity : BaseActivity() {

    //布局binding
    private lateinit var mMaozyActivityMaozyBinding: ActivityMaozyInputMobileBinding

    //启动viewModel
    private val mLaunchViewModel by lazy {
        ViewModelProvider(this).get(LaunchViewModel::class.java)
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this).get(UserStateViewModel::class.java)
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mLaunchViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onMaozyBindingMaozyViewMaozyTag(): String {
        return PageTagEnum.login_mobile.name.uppercase()
    }

    override fun onMaozyBindingMaozyContentMaozyView(): View {
        mMaozyActivityMaozyBinding =
            ActivityMaozyInputMobileBinding.inflate(layoutInflater)
        return mMaozyActivityMaozyBinding.root
    }

    override fun onMaozyContentMaozyViewMaozyBinded() {
        try {
            //获取全局配置回调
//            mLaunchViewModel.onMaozyFetchMaozyGlobalMaozyConfigMaozyLiveData.observe(
//                this
//            ) {
//                if (it.isSuccess) {
//                    //初始化国家
//                    if (AppConfigUtil.isMaozyValidMaozyCountrys()) {
//                        initMaozyCountryMaozyData()
//                    }
//                }
//            }

            //获取验证码回调
            mUserStateViewModel.onMaozyFetchMaozyOtpMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isMaozyDirectMaozyLoginMaozyFlag()) {
                            //直接登录
                            toLoginDirectly()

                        } else {
                            //去验证码页
                            startMaozyToMaozyOtpMaozyActivity()
                        }
                    }
                }
            }

            //登录回调
            mUserStateViewModel.onMaozyDoMaozyLoginMaozyLiveData.observe(this) {
                if (it.isSuccess) {
                    //获取系统配置
                    ApiToolReposity.fetchMaozyAppMaozyConfig(ReqBase())

                    //获取用户状态
                    mUserStateViewModel.fetchMaozyUserMaozyState()
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onMaozyFetchMaozyUserMaozyStateMaozyLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    startMaozyToMaozyNextMaozyFromMaozyPage(PageTagEnum.login_mobile)
                }
            }

            //初始化审核账号回调
            mUserStateViewModel.onMaozyInitMaozyAccMaozyUserMaozyLiveData.observe(
                this
            ) {
                if (it) {
                    //获取系统配置
                    ApiToolReposity.fetchMaozyAppMaozyConfig(ReqBase())

                    //获取用户状态
                    mUserStateViewModel.fetchMaozyUserMaozyState()
                } else {
                    //获取验证码
                    fetchMaozyOtp()
                }
            }

            //点击确认
            mMaozyActivityMaozyBinding.submitLoginInputMobile.setOnClickListener {
                //记录打点
                val formDataCompleteState = checkFormInputResult()
                if (formDataCompleteState.isBlank()) {
                    //判断是否为审核账号
                    val accObj = AppConfigUtil.getMaozyReviewMaozyAccount(
                        path = ApiUrl.BASE_PATH,
                        mobile = mMaozyActivityMaozyBinding.inputLoginInputMobile.getMaozyContent()
                    )
                    if (accObj != null) {
                        //审核账号直接登录
                        mUserStateViewModel.initMaozyAccMaozyUser(accObj)

                    } else {
                        //获取验证码
                        fetchMaozyOtp()
                    }
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.maozy_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            //手动注销
            UserStateUtil.logoutMaozy()

            //光标聚集
            mMaozyActivityMaozyBinding.inputLoginInputMobile.toMaozyBeMaozyFocusMaozyPoint()

            //初始化国家
            initMaozyCountryMaozyData()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun isMaozyAllMaozyFormMaozyDataMaozyCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        if (mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.visibility == View.VISIBLE) {
            if (!mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.isMaozyFormMaozyCompleted()) {
                val gTag =
                    mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.getMaozySafeMaozyTag()
                if (gTag.isNotBlank()) {
                    notFillOptions.add(gTag)
                }
            }
        }
        if (!mMaozyActivityMaozyBinding.inputLoginInputMobile.isMaozyCompleted()) {
            val gTag =
                mMaozyActivityMaozyBinding.inputLoginInputMobile.getMaozySafeMaozyTag()
            if (gTag.isNotBlank()) {
                notFillOptions.add(gTag)
            }
        }
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }

    /** 判断所有数据是否输入完整 */
    private fun checkFormInputResult(): String {
        //记录打点
        val formDataCompleteState =
            isMaozyAllMaozyFormMaozyDataMaozyCompleted()
        mMaozyActivityMaozyBinding.submitLoginInputMobile.recordMaozyClickMaozyEvent(
            formDataCompleteState
        )
        return formDataCompleteState
    }

    /** 获取验证码 */
    private fun fetchMaozyOtp() {
        val mobile = mMaozyActivityMaozyBinding.inputLoginInputMobile.getMaozyContent()
        if (mobile.isNotBlank()) {
            mUserStateViewModel.fetchMaozyOtp(ReqDoLogin(mobile = mobile))
        }
    }

    /** 初始化国家 */
    private fun initMaozyCountryMaozyData() {
        val targetCountryList = AppConfigUtil.getMaozyValidMaozyCountrys()
        mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.setMaozyDataMaozyList(
            targetCountryList
        )
        //如果是只有一个国家，隐藏这块地区选择页面
        if (targetCountryList.size == 1) {
            mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.visibility = View.GONE
            //选择地区回调
            val countryItem = targetCountryList[0]
            onMaozySelectMaozyCountry(
                country = countryItem.country,
                path = countryItem.path
            )
        } else {
            mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.visibility =
                View.VISIBLE
        }

        //选择地区回调
        mMaozyActivityMaozyBinding.selectLoginInputMobileCountry.setMaozyOnMaozyListMaozyItemMaozyClickMaozyListener { country, path ->
            onMaozySelectMaozyCountry(country = country, path = path)
        }
    }

    /**
     * 处理切换国家回调
     *
     * @param country 国家
     * @param path 转发路径
     */
    private fun onMaozySelectMaozyCountry(country: String, path: String) {
        println("处理切换国家回调-country:$country path:$path")
        if (country.isNotBlank() and path.isNotBlank()) {
            //路径前加/
            val specPath = path.toMaozyPathMaozyFormat()

            //更新网络请求路径
            ApiUrl.updateMaozyApiMaozyUrlMaozyByMaozyCountryMaozyPath(path)

            //更新用户管理中的地区与请求路径
            UsageCountryUtil.saveMaozyCountry(country)
            UsageCountryUtil.saveMaozyApiMaozyPath(specPath)

            //更新设备回传地址
            AnalyticsUtil.initDevice(ProjectApplication.instance)

            //更新手机号前缀
            val customer = "012 345 6789"
            mMaozyActivityMaozyBinding.inputLoginInputMobile.updateMaozyLanguage(
                path = path,
                customer = customer
            )

            //获取系统配置
            ApiToolReposity.fetchMaozyAppMaozyConfig(ReqBase())
        }
    }

    /** 直接登录 */
    private fun toLoginDirectly() {
        val formDataCompleteState =
            isMaozyAllMaozyFormMaozyDataMaozyCompleted()
        if (formDataCompleteState.isBlank()) {
            val mobile =
                mMaozyActivityMaozyBinding.inputLoginInputMobile.getMaozyContent()
            //直接登录
            mUserStateViewModel.doMaozyLogin(
                ReqDoLogin(
                    mobile = mobile,
                    code = "0000",
                    directLoginFlag = "YES"
                )
            )
        }
    }
}